import { getPage } from '../../utils/config';
import { http, $query, countMode } from '../../utils/utils';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        loading: 0,
        submitMat: 0,
        addressTip: true,
        addressPanelHeight: 0,
        orderInfo: {},
        cartId: [],
        addressId: '',
        buyCount: 1,
        pageSource: 0,
        sumPrice: 0,
        showCoupon: false,
        couponInfo: [],
        packetsPrice: 0,
        points: 0,
        platPoints: false,
        platPackets: false,
        platDiscount: 0,
    },

    toggle(type) {
        this.setData({
            [type]: !this.data[type]
        });
    },

    doNothing() {},

    /**
     * 选择收货地址
     */
    selectAddressClick() {
        wxApi.navigateTo(getPage.address, { mode: 1 })
    },

    /**
     * 买家留言
     */
    message: [],
    messageChange(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        const msg = e.detail.value;

        if(this.message.length){
            for(let i in this.message){
                if(this.message[i].shopid == data.shopId){
                    this.message[i].remark = msg;
                    break;
                }else if(i == this.message.length - 1){
                    this.message.push({
                        shopid: data.shopId,
                        remark: msg,
                    })
                }
            }
        }else{
            this.message.push({
                shopid: data.shopId,
                remark: msg,
            })
        }
    },

    /**
     * 优惠券显示
     */
    toggleCoupon() {
        this.toggle('showCoupon');
    },

    /**
     * 平台优惠券
     */
    platCouponClick(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        const orderInfo = this.data.orderInfo;
        const coupons = {
            parentId: data.parentId,
            coupons: orderInfo.plat_coupons
        }
        this.setData({
            couponInfo: coupons
        });
        this.toggle('showCoupon');
    },

    /**
     * 优惠抵扣
     */
    integralChange(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        const { orderInfo } = this.data;
        let platDiscount = 3;
        let parentId = -4;

        //震动
        wx.vibrateShort();

        //更新使用优惠方式
        if(data.id == 1){
            //如果红包未使用，则选择红包
            if(!this.data.platPackets){
                platDiscount = data.id;
                parentId = data.parentId;
            }
            //如果使用积分,则关闭
            if(this.data.platPoints){
                this.toggle('platPoints');
            }
            this.toggle('platPackets');
        }else if(data.id == 2){
            //如果积分未使用，则选择积分
            if(!this.data.platPoints){
                platDiscount = data.id;
                parentId = data.parentId;
            }
            //如果使用红包,则关闭
            if (this.data.platPackets) {
                this.toggle('platPackets');
            }
            this.toggle('platPoints');
        }

        this.setData({ platDiscount: platDiscount });
        //优惠计算
        this.sumCount(orderInfo, parentId);
        //重新定义优惠券
        this.setData({ 'orderInfo.couponsKey': -1 })
    },

    /**
     * 计算总价
     */
    sumCount(data, parentKey, couponsKey) {
        const orderInfo = data;
        const priceArr = [];
        const shippingfeeArr = [];
        let platDiscount = Number(this.data.platDiscount);
        let sumPrice = 0;
        let sumGoodsPrice = 0;
        let sumShippingfee = 0;
        //重新生成数据模型
        orderInfo.shops.forEach((parentItem, parentIndex) => {
            //邮费
            const shippingfee = parentItem.shippingfee;
            const coupons = parentItem.coupons;
            let sumAmount = 0;
            //重新计算总价
            parentItem.ProductList.forEach((item) => {
                const price = countMode.mul(item.order_price, item.product_count);
                sumAmount = countMode.add(sumAmount, price);
            });
            //加运费
            if (shippingfee && shippingfee > 0) {
                //商品邮费总价
                shippingfeeArr.push(shippingfee);
                //减去邮费后的价格
                sumAmount = countMode.add(sumAmount, shippingfee);
            }
            //减去优惠券
            if (coupons && coupons.length > 0) {
                //键入默认优惠券下标
                if (parentKey !== undefined && parentKey >= 0 && parentIndex === parentKey){
                    parentItem.couponsKey = couponsKey
                }else{
                    //判断是否使用过
                    if (typeof(parentItem.couponsKey) === 'undefined'){
                        parentItem.couponsKey = 0;
                    }
                }
                sumAmount = countMode.sub(sumAmount, coupons[parentItem.couponsKey].price);
            }
            //商店购买总价
            parentItem.sumAmount = sumAmount;
            //全部价格
            priceArr.push(sumAmount);
        });

        //计算总邮费
        shippingfeeArr.forEach((item) => {
            sumShippingfee = countMode.add(sumShippingfee, item);
        });

        //全部总价计算
        priceArr.forEach((item) => {
            sumPrice = countMode.add(sumPrice, item);
        });

        let packetsPrice = 0;
        let points = 0;

        //红包金额
        if(orderInfo.HB_Money > countMode.div(sumPrice, 2)){
            packetsPrice = countMode.div(sumPrice, 2)
        }else{
            packetsPrice = orderInfo.HB_Money;
        }

        //积分抵扣
        if (parseInt(countMode.div(orderInfo.User_Points, orderInfo.Points)) > countMode.div(sumPrice, 2)){
            points = countMode.div(sumPrice, 2) * orderInfo.Points;
        }else{
            points = orderInfo.User_Points;
        }

        /**
         * 平台优惠计算
         */
        let platPrice = 0;
        //-1 平台优惠券
        let couponPrice = 0;
        if (orderInfo.plat_coupons && orderInfo.plat_coupons.length){
            //如果出入parentKey小于0则是平台优惠
            if (parentKey !== undefined && parentKey < 0 && parentKey == -1){
                orderInfo.couponsKey = couponsKey;
            }else{
                if (typeof (orderInfo.couponsKey) === 'undefined') {
                    orderInfo.couponsKey = 0
                }
            }
            if (orderInfo.couponsKey >= 0){
                couponPrice = orderInfo.plat_coupons[orderInfo.couponsKey].price
            }
        }
        //-3 积分抵扣
        let pointsPrice = parseInt(countMode.div(points, orderInfo.Points));

        //平台优惠使用
        if (parentKey !== undefined && parentKey < 0){
            //选择优惠计算
            switch (parentKey){
                case '-1':
                    platPrice = couponPrice
                break;
                case '-2':
                    platPrice = packetsPrice
                break;
                case '-3':
                    platPrice = pointsPrice
                break;
            }
        }else{
            switch(platDiscount){
                case 0:
                    if(orderInfo.plat_coupons && orderInfo.plat_coupons.length){
                        //如果没有优惠券下标则取第一个，否则使用下标
                        if (typeof (orderInfo.couponsKey) === 'undefined') {
                            orderInfo.couponsKey = 0
                        }
                        platPrice = orderInfo.plat_coupons[orderInfo.couponsKey].price
                    }else{
                        platPrice = 0
                    }
                break;
                case 1:
                    platPrice = packetsPrice
                break;
                case 2:
                    platPrice = pointsPrice
                break;
            }
        }

        //计算总价
        sumPrice = countMode.sub(sumPrice, platPrice);
        //商品总价 = 合计 - 邮费
        sumGoodsPrice = countMode.sub(sumPrice, sumShippingfee);
        
        //更新数据
        this.setData({
            orderInfo: orderInfo,
            packetsPrice: packetsPrice,
            points: points,
            sumPrice: sumPrice,
            sumGoodsPrice: sumGoodsPrice,
            sumShippingfee: sumShippingfee,
        });
    },

    /**
     * 获取订单
     */
    getOrderInfo(cb, a = false) {
        const { userId, userRank, cartId, addressId } = this.data;
        http.post(api.default, {
            data: {
                action: 'ordersubmit-preview',
                userid: userId,
                user_rank: userRank,
                cart_id_list: cartId,
                address_id: addressId,
            }
        }, a).then((res) => {
            //如果有平台优惠券则使用
            this.setData({
                platDiscount: 0,
                packetsPrice: res.data.data.HB_Money,
                pointsPrice: res.data.data.User_Points,
            });
            //如果购物车进入，增加数量
            if(this.data.pageSource){
                this.setData({
                    buyCount: res.data.data.shops[0].ProductList[0].product_count
                })
            }
            //重构模型
            this.sumCount(res.data.data);
            //callback
            cb && cb();
        });
    },

    /**
     * 增加数量
     */
    stepperChange(e) {
        const count = e.detail;
        const data = e.currentTarget.dataset || e.target.dataset;
        const orderInfo = this.data.orderInfo;

        if (count) {
            http.post(api.default, {
                data: {
                    action: 'update_cart',
                    pcount: count,
                    recid: this.data.cartId,
                    userid: this.data.userId,
                }
            }).then((res) => {
                this.setData({
                    platDiscount: 0,
                    platPoints: false,
                    platPackets: false,
                })
                //订单信息更新
                this.getOrderInfo();
            })
        }
    },

    /**
     * 优惠券使用
     */
    getCoupons(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        const orderInfo = this.data.orderInfo;
        const coupons = {
            parentId: data.id,
            coupons: orderInfo.shops[data.id].coupons
        }
        this.setData({ couponInfo: coupons });
        this.toggle('showCoupon');
    },

    /**
     * 选择优惠券
     */
    couponTap(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        if(data.parentId == -1){
            if (this.data.platPackets) {
                this.toggle('platPackets');
            }
            if (this.data.platPoints) {
                this.toggle('platPoints');
            }
            this.setData({
                platDiscount: 0
            });
        }
        //重构模型
        this.sumCount(this.data.orderInfo, data.parentId, data.id);
        //关闭选择
        this.toggle('showCoupon');
    },

    /**
     * 结果数据
     */
    remarkData() {
        const orderInfo = this.data.orderInfo;
        let remark = [];

        orderInfo.shops.forEach((item) => {
            let data = {
                shopid: item.shopId,
                CouponId: 0,
                remark: '',
            };
            if(item.coupons && item.coupons.length) {
                data.CouponId = item.coupons[item.couponsKey].CouponId;
            }
            remark.push(data);
        });

        remark.forEach((item) => {
            this.message.forEach((key) => {
                if(item.shopid === key.shopid){
                    item.remark = key.remark
                }
            })
        })

        return remark;
    },

    /**
     * 选择地址更新价格
     */
    addressChange(id) {
        this.setData({ 
            addressId: id,
            platDiscount: 0,
            platPoints: false,
            platPackets: false,
        });
        //订单信息更新
        this.getOrderInfo();
    },

    /**
     * 提交账单
     */
    submitButtonClick() {
        const orderInfo = this.data.orderInfo;
        const platDiscount = Number(this.data.platDiscount);
        let couponsId = 0;
        const plat = {
            //1、平台优惠券 2、积分 3、红包抵扣
            DiscountType: 1,
            //优惠券id
            Coupon_Tid: 0,
            //积分值
            Points: 0,
            //红包抵扣金额
            DiscountAmount: 0,
        };
        
        //获取优惠券id
        if(orderInfo.plat_coupons && orderInfo.plat_coupons.length && platDiscount == 0){
            couponsId = orderInfo.plat_coupons[orderInfo.couponsKey].CouponId
        }

        switch (platDiscount){
            case 0:
                plat.DiscountType = 1;
                plat.Coupon_Tid = couponsId;
            break;
            case 1:
                plat.DiscountType = 3;
                plat.DiscountAmount = orderInfo.HB_Money;
            break;
            case 2:
                plat.DiscountType = 2;
                plat.Points = this.data.points;
            break;
        }

        http.post(api.default, {
            data: {
                action: 'ordersubmit',
                address_id: this.data.orderInfo.address.address_id,
                cart_id_list: this.data.cartId,
                userid: this.data.userId,
                user_rank: this.data.userRank,
                remark: JSON.stringify(this.remarkData()),
                platdiscount: JSON.stringify(plat),
            }
        }).then((res) => {
            const { data } = res.data;
            const { sumPrice, sumShippingfee, sumGoodsPrice, orderInfo  } = this.data;
            wxApi.redirectTo(getPage.checkout, { 
                orderSn: data.OrderSn,
                sumPrice: sumPrice,
                sumShippingfee: sumShippingfee,
                sumGoodsPrice: sumGoodsPrice,
                address: JSON.stringify(orderInfo.address),
            });
        })
    },

    /**
     * 滚动条函数--监听页面滚动
     */
    onPageScroll(e) {

        //重新获取底部高度
        $query.select('#submitBox', (res) => {
            this.setData({
                submitMat: res.height
            })
        });

        //地址栏效果
        if (e.scrollTop > this.data.addressPanelHeight) {
            this.setData({
                addressTip: false
            });
        } else {
            this.setData({
                addressTip: true
            });
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

        //携带参数
        if(Object.keys(options).length){
            this.setData({
                cartId: options.cartId.split('_'),
                pageSource: options.source,
            });
        }

        //判断是否登录
        app.getLogin().then((res) => {

            this.setData({
                logged: res.code,
                userId: res.data.user.user_id,
                userRank: res.data.user.user_rank,
            });

            //获取订单
            this.getOrderInfo(() => {
                //加载完成
                this.setData({ loading: 1 });
            });

        }).catch((res) => {
            this.setData({ logged: res });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        $query.select('#submitBox,#address-panel', (res) => {
            res.forEach((item) => {
                //底部浮动高
                if (item.id == 'submitBox') {
                    this.setData({
                        submitMat: item.height
                    })
                }

                //地址高度
                if (item.id == 'address-panel') {
                    this.setData({
                        addressPanelHeight: item.height
                    })
                }

            })
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})